<template>
  <div>
    <PageWrapper contentBackground contentClass="flex" dense contentFullHeight fixedHeight>
      <ImagePreview :imageList="imgList" />
      <Tabs v-model:activeKey="activeKeyRef" size="small">
        <template #rightExtra>
          <Space :size="8">
            <a-button type="success" @click="handleAddPlace"> 添加场所2 </a-button>
            <a-button type="primary" @click="handleReloadCurrent"> 刷新当前页 </a-button>
            <a-button type="primary" @click="handleReload"> 返回第一页 </a-button>
          </Space>
        </template>
        <template #leftExtra>
          <Tooltip :title="searchInfo.id" color="#108ee9">
            <Tag color="processing"> 场所综合隐患 </Tag>
          </Tooltip>
          <Divider type="vertical" />
        </template>
        <TabPane key="Commercial" tab="商业场所">
          <BasicTable @register="registerTableCommercial" :searchInfo="searchInfo">
            <template #boolPic="{ record, column }">
              {{ record[column.dataIndex] ? '是' : '否' }}
              <TableAction
                :actions="[
                  {
                    icon: 'ant-design:picture',
                    tooltip: '预览',
                    onClick: handlePreview.bind(null, record, column.dataIndex),
                  },
                ]"
              />
            </template>
            <template #renderInspectorSign="{ record, column }">
              <Avatar
                shape="square"
                alt="暂无签名"
                :src="getAvatarView(record[column.dataIndex])"
                style="width: 100px; height: 100px; margin: 2px"
              >
                暂无签名
              </Avatar>
            </template>
            <template #toolbarLeft> </template>
            <template #action="{ record }">
              <TableAction
                :actions="[
                  {
                    icon: 'clarity:note-edit-line',
                    tooltip: '审核',
                    onClick: handleAudit.bind(null, record),
                  },
                  {
                    icon: 'ant-design:align-right-outlined',
                    tooltip: '详情',
                    onClick: handleDetail.bind(null, record, '0'),
                  },
                ]"
              />
            </template>
          </BasicTable>
        </TabPane>
        <TabPane key="Resident" tab="居住场所">
          <BasicTable @register="registerTableResident" :searchInfo="searchInfo">
            <template #boolPic="{ record, column }">
              {{ record[column.dataIndex] ? '是' : '否' }}
              <TableAction
                :actions="[
                  {
                    icon: 'ant-design:picture',
                    tooltip: '预览',
                    onClick: handlePreview.bind(null, record, column.dataIndex),
                  },
                ]"
              />
            </template>
            <template #renderInspectorSign="{ record, column }">
              <Avatar
                shape="square"
                alt="暂无签名"
                :src="getAvatarView(record[column.dataIndex])"
                style="width: 100px; height: 100px; margin: 2px"
              >
                暂无签名
              </Avatar>
            </template>
            <template #toolbarLeft> </template>
            <template #action="{ record }">
              <TableAction
                :actions="[
                  {
                    icon: 'clarity:note-edit-line',
                    tooltip: '审核',
                    onClick: handleAudit.bind(null, record),
                  },
                  {
                    icon: 'ant-design:align-right-outlined',
                    tooltip: '详情',
                    onClick: handleDetail.bind(null, record, '1'),
                  },
                ]"
              />
            </template>
          </BasicTable>
        </TabPane>
      </Tabs>
    </PageWrapper>
    <AuditModal @register="registerModalResident" @success="handleSuccess" />
    <AuditModal @register="registerModalCommercial" @success="handleSuccess" />
    <AddPlaceModal @register="registerModalAddPlace" @success="handleSuccess" />

    <Drawer5 @register="register5">
      <template #drawContent>
        <DetailView :hid="searchInfo.id" :pid="detailRcdRef" :typ="typRef" ref="detailViewRef" />
      </template>
    </Drawer5>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, reactive } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import {
    getCommercialBasicColumns,
    getResidentBasicColumns,
    searchFormSchema,
  } from './tableData';
  import { PageWrapper } from '/@/components/Page';
  import { createImgPreview, ImagePreview } from '/@/components/Preview/index';
  import { placeResidentListApi, placeCommercialListApi } from '/@/api/demo/integrationtable';
  import { useModal } from '/@/components/Modal';
  import { default as FetchHouseTable } from '/@/views/house/FetchTable.vue';
  import AuditModal from './AuditModal.vue';
  import AddPlaceModal from './AddPlaceModal.vue';
  import { Tabs, Space, Divider, Tag, Avatar, Tooltip } from 'ant-design-vue';
  import type { FetchParams } from '/@/components/Table/src/types/table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useGo } from '/@/hooks/web/usePage';
  import { useUserStore } from '/@/store/modules/user';
  import { useGlobSetting } from '/@/hooks/setting';
  import { useDrawer } from '/@/components/Drawer';
  import Drawer5 from '/@/views/detail/Drawer5.vue';
  import DetailView from './detail.vue';

  const globSetting = useGlobSetting();
  const userStore = useUserStore();
  const tk = userStore.getToken;
  const { createMessage, createErrorModal } = useMessage();

  export default defineComponent({
    components: {
      Drawer5,
      DetailView,
      BasicTable,
      Tabs,
      Avatar,
      Divider,
      Tag,
      Space,
      Tooltip,
      TabPane: Tabs.TabPane,
      PageWrapper,
      TableAction,
      AuditModal,
      FetchHouseTable,
      ImagePreview,
      AddPlaceModal,
    },
    props: {
      houseId: {
        type: String,
        default: '',
      },
    },
    setup(props) {
      const go = useGo();
      const viewList = ref(true);
      const searchInfo = reactive<Recordable>({ id: props.houseId });
      const activeKeyRef = ref('Commercial');
      const imgList: string[] = [];
      const detailRcdRef = ref('');
      const typRef = ref('');
      const detailViewRef = ref();

      const [registerModalResident, callbackUseModalResident] = useModal();
      const [registerTableResident, callbackUseTableResident] = useTable({
        api: placeResidentListApi,
        columns: getResidentBasicColumns(),
        pagination: { pageSize: 10 },
        useSearchForm: true,
        bordered: true,
        formConfig: {
          schemas: searchFormSchema,
        },
        handleSearchInfoFn(info) {
          console.log('handleSearchInfoFn', info);
          return info;
        },
        actionColumn: {
          width: 120,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
      });

      const [registerModalAddPlace, callbackModalAddPlace] = useModal();

      const [registerModalCommercial, callbackUseModalCommercial] = useModal();
      const [registerTableCommercial, callbackUseTableCommercial] = useTable({
        api: placeCommercialListApi,
        columns: getCommercialBasicColumns(),
        pagination: { pageSize: 10 },
        useSearchForm: true,
        bordered: true,
        formConfig: {
          schemas: searchFormSchema,
        },
        handleSearchInfoFn(info) {
          console.log('handleSearchInfoFn', info);
          return info;
        },
        actionColumn: {
          width: 120,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
      });

      function reload(opt?: FetchParams | undefined) {
        if (activeKeyRef.value == 'Commercial') {
          callbackUseTableCommercial.reload(opt);
        } else {
          callbackUseTableResident.reload(opt);
        }
      }
      function openModal(props?: boolean | undefined, data?: any, openOnSet?: boolean | undefined) {
        if (activeKeyRef.value == 'Commercial') {
          callbackUseModalCommercial.openModal(props, data, openOnSet);
        } else {
          callbackUseModalResident.openModal(props, data, openOnSet);
        }
      }

      function handleAddPlace() {
        console.log(searchInfo);
        callbackModalAddPlace.openModal(true, { record: { id: searchInfo.id } });
      }

      function handleReloadCurrent() {
        reload();
      }

      function handleSwitchMode() {
        viewList.value = !viewList.value;
      }

      function onHouseSelected(houseId: string) {
        searchInfo.id = houseId;
        reload();
      }
      function getAvatarView(avatarId) {
        if (avatarId) {
          const uril = `${globSetting.apiBaseUrl}/api/v1/images33334343/${avatarId}?access_token=${tk}`;
          return uril;
        }

        return '';
      }
      function handleAudit(record: Recordable) {
        openModal(true, {
          record,
          isUpdate: true,
        });
      }
      const [register5, { openDrawer: openDrawer5, setDrawerProps }] = useDrawer();
      function handleDetail(record: Recordable, typ: string) {
        //go(`/danger/fire/detail/${record['id']}?typ=${typ}&hid=${searchInfo.id}`);
        detailRcdRef.value = record['id'];
        typRef.value = typ;
        setDrawerProps({
          destroyOnClose: true,
          showDetailBack: false,
          afterVisibleChange: (visible: boolean) => {
            if (visible) {
              detailViewRef.value.locMap();
            }
          },
        });
        openDrawer5(true);
      }

      function handlePreview(record: Recordable, index: any) {
        const photos = record[`${index}Photos`];
        const onImgLoad = ({ index, url, dom }) => {
          console.log(`第${index + 1}张图片已加载，URL为：${url}`, dom);
        };
        imgList.length = 0;
        if (photos) {
          photos.forEach((ele) => {
            if (ele)
              imgList.push(`${globSetting.apiBaseUrl}/api/v1/images4ggggg/${ele}?access_token=${tk}`);
          });
        }
        if (imgList.length > 0) {
          // 可以使用createImgPreview返回的 PreviewActions 来控制预览逻辑，实现类似幻灯片、自动旋转之类的骚操作
          createImgPreview({
            imageList: imgList,
            defaultWidth: 700,
            rememberState: true,
            onImgLoad,
          });
        } else {
          createErrorModal({ title: '提示', content: '暂无图片' });
        }
      }

      function handleReload() {
        reload({
          page: 1,
        });
      }
      function handleSuccess() {
        reload();
      }
      return {
        imgList,
        registerModalResident,
        registerModalCommercial,
        registerTableResident,
        registerTableCommercial,
        handleAudit,
        handleDetail,
        handlePreview,
        handleReloadCurrent,
        handleSwitchMode,
        handleReload,
        handleSuccess,
        onHouseSelected,
        getAvatarView,
        activeKeyRef,
        searchInfo,
        detailRcdRef,
        detailViewRef,
        typRef,
        register5,
        handleAddPlace,
        registerModalAddPlace,
      };
    },
  });
</script>
